package com.blankii.androidlibrary.utils

import android.annotation.SuppressLint
import java.text.SimpleDateFormat
import java.util.Date

/**
 * author: blankii
 * created on: 2024/12/18 17:08
 * description: 计算某一个方法的执行时间
 */
object OptimizeHelper {
    @SuppressLint("SimpleDateFormat")
    private val sdf: SimpleDateFormat = SimpleDateFormat("HH:mm:ss.SSSS")

    interface Task {
        fun execute()
    }


    /**
     * 检测一个函数的执行时间
     *
     * 调用按理
     * OptimizeHelper.check("你好", object : OptimizeHelper.Task {
     *             override fun execute() {
     *                 Thread.sleep(3000)
     *             }
     *         })
     * 打印日志：
     * [你好]
     * 开始16:14:47.0282
     * 结束16:14:50.0288
     * 耗时：3.006秒
     */
    fun check(title: String, task: Task) {
        var title = title
        title = "[$title]\n"
        print(title)
        System.out.print(("开始" + sdf.format(Date())).toString() + "\n")
        val beginTime = System.currentTimeMillis()
        task.execute()
        val endTime = System.currentTimeMillis()
        val theTime = (endTime - beginTime) / 1000.0
        System.out.print(("结束" + sdf.format(Date())).toString() + "\n")
        print("耗时：" + theTime + "秒\n")
        print("---------------------------------")
    }
}